//
//  SWDownloaderManager.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/10/8.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation

private let _manager:SWDownloadManager = SWDownloadManager()
class SWDownloadManager: NSObject
{
    var basePath:String = ""
    
    private var _launch:Bool = false
    private var _fileManager = FileManager.default
    private var _tasks:[SWDownloadTask] = []
    private var _dataPath:String = ""
    private var _index:Int = 0
    private var _currentLoader:Downloader?
    private var _task:SWDownloadTask?
    private let ioQueue = DispatchQueue(label: "SWDownloadManager.ioQueue", attributes: .concurrent)
    
    private let _queue:OperationQueue = OperationQueue()
    
    //下载进展情况保存在本地，app打开后在wifi情况下进行上传
    class func sharedManager() -> SWDownloadManager
    {
        return _manager
    }
    
    override init() {
        //并行下载数
        _queue.maxConcurrentOperationCount = 3
        //print("SWDownloadManager init")
    }
    
    func launch()
    {
        if !_launch
        {
            _launch = true
            
            //页面的背景存在多本相册共用的可能性，因此放在公共目录中
            let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).valueAt(0) ?? ""
            basePath = "\(documentPath)/publicdata"
            _dataPath = "\(documentPath)/downloadtask.data"
            if !_fileManager.fileExists(atPath: basePath)
            {
                try? _fileManager.createDirectory(atPath: basePath, withIntermediateDirectories: true, attributes: nil)
            }
            
            pause()
            //未完成任务下载
            if let tasks = SWCacheManager.sharedManager().readCache(_dataPath) as? [SWDownloadTask]
            {
                for task in tasks
                {
                    if let relativePath = task.relativePath, relativePath != ""
                    {
                        task.localPath = fetchStorePath(relativePath: relativePath)
                        if !_fileManager.fileExists(atPath: task.localPath)
                        {
                            //print("!fileExistsAtPath", task.localPath)
                            task.finished = false
                        }
                        else
                        {
                            task.finished = true
                        }
                        addTask(task)
                    }
                }
                
            }//end if tasks
            
            resume()
        }
    }
    
    func pause()
    {
        _queue.isSuspended = true
    }
    
    func resume()
    {
        _queue.isSuspended = false
    }
    
    //通过图片URL获取本地缓存图片
    func getImage(_ URL:String) -> UIImage?
    {
        return FileUtility.imageDataFromPath(fetchStorePath(url:URL), scale: 1)
    }
    
    //获取原图存储路径
    func fetchStorePath(url:String) -> String
    {
        let path:String = "\(basePath)/\(fetchRelativePath(url))"
        return path
    }
    
    func fetchStorePath(relativePath path:String) -> String
    {
        let path:String = "\(basePath)/\(path)"
        return path
    }
    
    //获取相对路径
    func fetchRelativePath(_ url:String) -> String
    {
        return SWMD5.md532BitUpper(url)
    }
    
    private var _addTaskIntervalID:String = ""
    //添加下载任务，如果未完成的任务队列中含有同张图片，则进行覆盖合并
    //下载背景小图、大图；合成图小图
    //返回值可加载
    @discardableResult
    func addTask(_ task:SWDownloadTask, priority:Operation.QueuePriority = .normal) -> Bool
    {
        //过滤无效任务
        guard let localPath = task.localPath,let remoteURL = task.remoteURL, localPath != "" && remoteURL != "" else{
                return false
        }
        
        //如果队列中未包含此项或者此项未下载完成
        var finished:Bool = true
        if let index = _tasks.index(where: {($0.remoteURL ?? "") == (task.remoteURL ?? "")}),
           let aTask = _tasks.valueAt(index)
        {
            if !_fileManager.fileExists(atPath: task.localPath)
            {
                task.finished = false
                aTask.finished = false
                finished = false
            }
        }
        else
        {
            finished = task.finished ?? false
            _tasks.append(task)
        }
        
        var executable:Bool = false
        if let operations = _queue.operations as? [SWDownloadOperation],
           let index = operations.index(where: {$0.remoteURL == remoteURL}),
           let operation = operations.valueAt(index)
        {
            executable = true
            operation.queuePriority = priority
            print("提高优先级")
        }
        else
        {
            if !finished
            {
                executable = true
                let operation = SWDownloadOperation(task: task)
                addOperation(operation, priority: priority)
                print("_queue.operations:", _queue.operations.count)
            }
        }
        
        clearTimeout(_addTaskIntervalID)
        _addTaskIntervalID = setTimeout(0.5, closure: {[weak self] in
            //self?.load()
            self?.save()
        })
        
        return executable
    }
    
    func addOperation(_ operation:SWDownloadOperation, priority:Operation.QueuePriority)
    {
        operation.queuePriority = priority
        operation.successCallback = {[weak self] in self?.save()}
        _queue.addOperation(operation)
    }
    
    /**
    //返回值可加载
    func load(task:SWDownloadTask? = nil) -> Bool
    {
        if let task = task
        {
            if let index = _tasks.indexOf({($0.remoteURL ?? "") == (task.remoteURL ?? "")}),
               let aTask = _tasks.valueAt(index) where !(aTask.finished ?? false)
            {
                //将未完成的任务提前执行
                _tasks.removeAtIndexSafely(index)
                _tasks.insert(aTask, atIndex: 0)
            }
            
            if let currentRemoteURL = _task?.remoteURL where currentRemoteURL != "" && task.remoteURL != currentRemoteURL
            {
                _currentLoader?.cancel()
            }
        }
        
        guard let task = getUnloadedTask() else{
            return false
        }
        
        print("load tasks:", _tasks.count, task.finished)
        if !(task.finished ?? false)
        {
            print("task no finished")
        }
        
        _task = task
        
        return true
    }**/
    
    //通过URL获取下载任务
    func getTaskByURL(_ url:String) -> SWDownloadTask?
    {
        return _tasks.filter({($0.remoteURL ?? "") == url}).valueAt(0)
    }
    
    private func save()
    {
        SWCacheManager.sharedManager().writeCache(_tasks, path: _dataPath)
    }
    
    /**
    private let MaxRetryTimes:Int = 2
    private func getUnloadedTask() -> SWDownloadTask?
    {
        for task in _tasks
        {
            //未下载完成而且重试次数2次以下的才进行下载
            var finished:Bool = task.finished ?? false
            if finished
            {
                finished = _fileManager.fileExistsAtPath(task.localPath)
                task.finished = finished
            }
            
            if !finished && Int(task.retryTimes ?? 0) < MaxRetryTimes
            {
                return task
            }
        }
        return nil
    }**/
    
    
}
